package com.ltedu.oss.storage.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ltedu.common.enums.ErrorCodeEnum;
import com.ltedu.common.exception.BaseException;
import com.ltedu.common.utils.UUIDUtils;
import com.ltedu.oss.domain.FileInfo;
import com.ltedu.oss.mapper.FileInfoMapper;
import com.ltedu.oss.storage.Storage;
import com.ltedu.oss.utils.FileKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * @className: AbstractStorage
 * @auther: Jerry
 * @date: 2020/11/26 10:44
 * @desctiption: TODO
 * @version: 1.0
 */
public abstract class AbstractStorage implements Storage {

    @Autowired
    private FileInfoMapper fileInfoMapper;

    /**
     * 验证文件
     *
     * @param file 文件
     */
    protected void validateFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new BaseException(ErrorCodeEnum.NOT_FILE);
        }

        if (!FileKit.checkFileType(file.getOriginalFilename())) {
            throw new BaseException(ErrorCodeEnum.INVALID_FILE_TYPE);
        }
    }

    /**
     * 上传
     *
     * @param file 文件
     * @return {@link String}* @throws Exception 异常
     */
    @Override
    public String store(MultipartFile file) throws Exception {
        validateFile(file);
        return writeToStore(file.getBytes(), file.getOriginalFilename());
    }

    /**
     * 文件上传并返回路径
     *
     * @param bytes            字节
     * @param originalFilename 原始文件名
     * @return {@link String}* @throws Exception 异常
     */
    @Override
    public String writeToStore(byte[] bytes, String originalFilename) throws Exception {
        QueryWrapper<FileInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("file_name", FileKit.getFilename(originalFilename));
        FileInfo fileInfo = fileInfoMapper.selectOne(queryWrapper);
        if (fileInfo != null){
            return fileInfo.getFileUrl();
        }
        String filePath = new DateTime().toString("yyyy/MM/dd") + "/" + UUIDUtils.generatorUUId() +  FileKit.getSuffix(originalFilename);
        String path = writeToStore(bytes, filePath);

        // 图片入库
        fileInfo = new FileInfo();
        fileInfo.setFileName(FileKit.getFilename(originalFilename));
        fileInfo.setFileSize(Long.valueOf(bytes.length));
        fileInfo.setFileUrl(path);
        fileInfo.setGmtCreate(new Date());
        fileInfoMapper.insert(fileInfo);
        return path;
    }
}
